﻿using Puppy.Scheduler.Tasks;
using System;
using System.Threading;

namespace Puppy.Scheduler.Common
{
    /// <summary>
    /// 存储任务实体
    /// </summary>
    public class ThreadLocalStore : IDisposable
    {
        private static ThreadLocal<TaskEntity> TaskEntityThreadLocal { get; set; }

        private static ThreadLocal<AtomicLong> TaskIdThreadLocal { get; set; }

        public static TaskEntity GetTask()
        {
            return TaskEntityThreadLocal.Value;
        }

        public static void SetTask(TaskEntity taskEntity)
        {
            TaskEntityThreadLocal.Value = taskEntity;
        }

        public static AtomicLong GetTaskIdLocal()
        {
            if (TaskIdThreadLocal.Value == null)
                TaskIdThreadLocal.Value = new AtomicLong(0);

            return TaskIdThreadLocal.Value;
        }

        public static void Clear()
        {
            TaskEntityThreadLocal?.Dispose();
            TaskIdThreadLocal?.Dispose();
        }

        public void Dispose()
        {
            Clear();
        }
    }
}
